package com.platform.web.utils;

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import org.springframework.http.HttpStatus;
import java.util.Map;
import lombok.Data;


@Data
@ApiModel("统一响应")
public class CommonResult<T> {

	public static final String UNKNOWN_ERROR_MESSAGE ="未知异常，请联系管理员";
	public static final String DEF_ERROR_MESSAGE = "系统繁忙，请稍候再试";
	public static final String HYSTRIX_ERROR_MESSAGE = "请求超时，请稍候再试";

	public static final int SUCCESS_CODE = 0;

	@ApiModelProperty(value = "响应编码:0/200-请求处理成功，其他表示失败")
	private Integer code;

	@ApiModelProperty(value = "响应消息")
	private String msg;

	@ApiModelProperty(value = "响应结果")
	private T data;

	@ApiModelProperty(value = "附加数据")
	private Map<String, Object> extra;


	private CommonResult() {
		super();
	}

	public CommonResult(int code, T data, String msg) {
		this.code = code;
		this.data = data;
		this.msg = msg;
	}


	public static <E> CommonResult<E> error() {
		return error(null);
	}

	public static <E> CommonResult<E> error(String msg) {
		return error(HttpStatus.INTERNAL_SERVER_ERROR.value(), msg);
	}

	public static <E> CommonResult<E> error(Integer code, String msg) {
		return  new CommonResult<>( code, null, msg==null||msg.isEmpty()? UNKNOWN_ERROR_MESSAGE : msg);
	}


	public static <E> CommonResult<E> success() {
		return new CommonResult<>(SUCCESS_CODE, null, null);
	}

	public static <E> CommonResult<E> success(E data) {
		return new CommonResult<>(SUCCESS_CODE, data, null);
	}

	public static <E> CommonResult<E> success(E data, String msg) {
		return new CommonResult<>(SUCCESS_CODE, data, msg);
	}


	/**
	 * 附加数据
	 * @param key
	 * @param value
	 * @return
	 */
	public CommonResult<T> put(String key, Object value) {
		if (this.extra == null) {
			this.extra = Maps.newHashMap();
		}
		this.extra.put(key, value);
		return this;
	}


	/**
	 * 附加数据
	 * @param key
	 * @param value
	 * @return
	 */
	public CommonResult<T> putAll(Map<String,Object> extra) {
		if (this.extra == null) {
			this.extra = Maps.newHashMap();
		}
		this.extra.putAll(extra);
		return this;
	}

	
	
	
	/**
	 * RPC调用判断是否成功
	 * @return
	 */
	public Boolean getIsSuccess() {
		return this.code == SUCCESS_CODE || this.code == 200;
	}

	/**
	 * 逻辑处理是否失败
	 * @return
	 */
	public Boolean getIsError() {
		return !getIsSuccess();
	}

	@Override
	public String toString() {
		return JSONObject.toJSONString(this);
	}

}
